package com.lbw.Server.provider;


import com.lbw.Server.ratelimit.provider.RateLimitProvider;
import com.lbw.Server.serviceRegister.ServiceRegister;
import com.lbw.Server.serviceRegister.impl.ZKServiceRegister;
import lombok.Data;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lbwxxc
 * @date 2025/2/18 17:09
 * @description: 本地服务存放器
 */
@Data
public class ServiceProvider {

    private Map<String, Object> interfaceProvider;
    private int port;
    private String host;
    //注册服务类
    private ServiceRegister serviceRegister;
    //限流器
    private RateLimitProvider rateLimitProvider;
    public ServiceProvider(String host,int port) {
        this.host=host;
        this.port=port;
        this.interfaceProvider=new HashMap<>();
        this.serviceRegister=new ZKServiceRegister();
        this.rateLimitProvider = new RateLimitProvider();
    }

    public void provideServiceInterface(Object service, boolean canRetry) {

        String serviceName = service.getClass().getName();
        Class<?>[] interfaceName = service.getClass().getInterfaces();

        for (Class<?> clazz : interfaceName) {
            //将接口的全限定名和对应的服务的实例添加到map
            interfaceProvider.put(clazz.getName(), service);
            serviceRegister.register(clazz.getName(), new InetSocketAddress(host, port), canRetry);
            System.out.println(clazz.getName() + new InetSocketAddress(host, port));
        }
    }

    public Object getService(String interfaceName) {
        return interfaceProvider.get(interfaceName);
    }
}
